package com.wholesale;

import java.math.BigDecimal;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalPayment;
import com.wholesale.beans.Order;
import com.wholesale.datas.PaypalPanelResultDelegate;
import com.wholesale.datas.WebServiceClient;
import com.wholesale.utils.Constants;
import com.wholesale.utils.Maths;

/**
 * paypal付款layout
 * 
 * @author Administrator
 * 
 */
public class PaypalLayout extends LinearLayout implements OnClickListener {
	private static ViewFlipper viewFlipper;
	private static Context context;
	private static Order order;
	private static PaypalLayout currentInstance;
	private View baseView;

	private TextView txtGoodsAmount;
	private TextView txtShippingFee;
	private TextView txtUseBalance;
	private TextView txtShouldPay;
	private LinearLayout paypalLayout;
	private LinearLayout loadingPaypalLayout;
	private Button cancelBtn;

	public static Handler paypalHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 接收来自PaypalPanelResultDelegate的消息
			if (msg.what == 2007) {
				// 0-success 1-failed 2-cancle
				switch (msg.arg1) {
				case 0:
					// success
					boolean result = WebServiceClient.setPaypalId(
							order.getOrderSn(), (String) msg.obj,
							order.getUserId(),
							Constants.loginResponse.getUserToken());
					if (result) {
						Toast.makeText(context, "payment success.", 3000)
								.show();
					} else {
						Toast.makeText(context,
								"error,but payment success. Pls Contact Us!",
								9000).show();
					}
					viewFlipper.showPrevious();
					viewFlipper.removeView(currentInstance);
					break;
				case 1:
					// failed
					Toast.makeText(context, "payment failed. please retry it.",
							8000).show();
					// viewFlipper.showPrevious();
					// viewFlipper.removeView(currentInstance);
					currentInstance.initPaypal(order);
					break;
				case 2:
					// cancle
					Toast.makeText(context, "payment canceled.", 6000).show();
					// viewFlipper.showPrevious();
					// viewFlipper.removeView(currentInstance);
					currentInstance.initPaypal(order);
					break;
				}
			}
		}
	};

	public Handler initHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 2001) {
				// 生成按钮
				initPaypalButton();
			}
		};
	};

	CheckoutButton paymentBtn;

	protected void initPaypal(Order order) {
		Thread t = new Thread() {
			@Override
			public void run() {
				initLibrary();
				initHandler.sendEmptyMessage(2001);
			}
		};
		t.start();
		loadingPaypalLayout.setVisibility(View.VISIBLE);

	}

	private void initPaypalButton() {
		// 生成按钮
		try {
			paypalLayout.removeView(paymentBtn);
		} catch (Exception e) {
		}
		loadingPaypalLayout.setVisibility(View.GONE);
		PayPal pp = PayPal.getInstance();
		paymentBtn = pp.getCheckoutButton(context, PayPal.BUTTON_194x37,
				CheckoutButton.TEXT_PAY);
		paymentBtn.setOnClickListener(this);
		paymentBtn.setGravity(Gravity.CENTER_HORIZONTAL);
		paypalLayout.addView(paymentBtn);
	}

	private void doPalpayPay() {
		PayPalPayment payment = new PayPalPayment();
		payment.setCurrencyType("USD");
		payment.setRecipient(Constants.paypalReceiver);
		payment.setSubtotal(new BigDecimal(Double.toString(shouldPay)));
		payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
		payment.setMerchantName("Wholesale dress");
		payment.setDescription("WholeSale Payment");
		payment.setCustomID("8873482296");
		payment.setIpnUrl("http://www.exampleapp.com/ipn");
		Intent checkoutIntent = PayPal.getInstance().checkout(payment, context,
				new PaypalPanelResultDelegate());
		((Activity) context).startActivityForResult(checkoutIntent,
				MyOrdersDetailLayout.request);
	}

	private void initLibrary() {
		PayPal pp = PayPal.getInstance();
		if (pp == null) {
			pp = PayPal.initWithAppID(context, Constants.paypalAppId,
					MyOrdersDetailLayout.server);
			pp.setLanguage("en_US");
			pp.setFeesPayer(PayPal.FEEPAYER_EACHRECEIVER);
			pp.setShippingEnabled(false);
			pp.setDynamicAmountCalculationEnabled(false);
		}
	}

	private double shouldPay;

	public PaypalLayout(Context context, final ViewFlipper viewFlipper,
			Order order) {
		super(context);
		currentInstance = this;
		PaypalLayout.viewFlipper = viewFlipper;
		PaypalLayout.context = context;
		PaypalLayout.order = order;
		// 加载需要的属性，加载方法一的子Layout
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(
				R.layout.paypal_layout, this);

		txtGoodsAmount = (TextView) baseView
				.findViewById(R.id.txtPaypalGoodsAmount);
		txtShippingFee = (TextView) baseView
				.findViewById(R.id.txtPaypalShippingFee);
		txtShouldPay = (TextView) baseView
				.findViewById(R.id.txtPaypalShouldPay);
		txtUseBalance = (TextView) baseView
				.findViewById(R.id.txtPaypalUseBalance);
		paypalLayout = (LinearLayout) baseView
				.findViewById(R.id.paypalLayout_content);
		loadingPaypalLayout = (LinearLayout) baseView
				.findViewById(R.id.loadingPaypal_layout);
		cancelBtn = (Button) baseView.findViewById(R.id.buttonCheckoutLater);
		cancelBtn.setOnClickListener(this);
		initPaypal(order);

		// 设置界面显示
		txtGoodsAmount.setText("$" + order.getGoodsAmount());
		txtShippingFee.setText("$"
				+ Constants.getTwoDecimalFloor(order.getShippingFee()));
		txtUseBalance.setText("$" + order.getSurplus());
		shouldPay = Maths.sub(
				Maths.add(order.getGoodsAmount(), order.getShippingFee()),
				order.getSurplus());
		txtShouldPay.setText("$" + shouldPay);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.leftBtn:
		case R.id.buttonCheckoutLater:
			viewFlipper.showPrevious();
			viewFlipper.removeView(this);
			break;
		default:
			break;
		}
		if (v instanceof CheckoutButton) {
			doPalpayPay();
		}

	}
}
